package com.fast.security.handler;

import com.fast.constants.CacheConstants;
import com.fast.pojo.AjaxResult;
import com.fast.pojo.dto.SecurityUserDTO;
import com.fast.utils.redis.RedisCache;
import com.fast.utils.response.ResponseUtil;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author ruan cai yuan
 * @version 1.0
 * @fileName com.fast.security.handler.LogoutHandlerImpl
 * @description: TODO
 * @since 2024/6/23 15:18
 */
@Component
public class LogoutHandlerImpl implements LogoutHandler {
    @Resource
    private RedisCache redisCache;

    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        // 清空redis中的用户信息
        Object principal = authentication.getPrincipal();
        if (principal instanceof SecurityUserDTO) {
            SecurityUserDTO dto = (SecurityUserDTO) principal;
            // 清空redis中的用户信息
            redisCache.deleteObject(CacheConstants.LOGIN_INFO_KEY + dto.getUsername());
            //清空security 上下文 filterChain
            SecurityContextHolder.clearContext();
            //返回信息给前端
            AjaxResult success = AjaxResult.success("注销成功");
            ResponseUtil.responseData(response, success, MediaType.APPLICATION_JSON_VALUE);
        }

    }
}
